package com.zhhtech.zhh.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.kingja.loadsir.core.LoadService
import com.zhhtech.zhh.bean.FuZhai
import com.zhhtech.zhh.databinding.FragmentFuZhaiBinding
import com.zhhtech.zhh.databinding.ItemFuzhaiBinding
import com.zhhtech.zhh.ui.activity.main.FuZhaiAddActivity
import com.zhhtech.zhh.ui.base.BaseFragment
import com.zhhtech.zhh.ui.base.BaseRecyclerAdapter
import com.zhhtech.zhh.ui.ext.showEmptyCallback
import com.zhhtech.zhh.ui.ext.showLoadingBeforeSuccessCallback
import com.zhhtech.zhh.ui.helper.loadsir.registerLoadSir
import com.zhhtech.zhh.ui.utils.SPUtils
import java.math.BigDecimal

class FuZhaiFragment : BaseFragment<FragmentFuZhaiBinding>() {
    private val mAdapter = FuZhaiAdapter()
    private lateinit var loadService: LoadService<*>

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        bindViewClick(vb.llAdd)
        loadService = vb.rlRoot.registerLoadSir(::onLoad)
        vb.rvList.layoutManager = LinearLayoutManager(context)
        vb.rvList.adapter = mAdapter
        onLoad()
    }

    private fun onLoad() {
        loadService.showLoadingBeforeSuccessCallback()
        val fuzhais =
            JSON.parseArray(SPUtils.getString("fuzhai", "[]").ifBlank { "[]" }, FuZhai::class.java)
        mAdapter.datas = ArrayList(fuzhais)
        mAdapter.notifyDataSetChanged()
        if (fuzhais?.isEmpty() == true) {
            loadService.showEmptyCallback()
        } else {
            loadService.showSuccess()
        }
        vb.tvFz.text =
            fuzhais?.map { it.jine.toBigDecimal() }?.reduce(BigDecimal::add)?.toPlainString() ?: "0"
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.llAdd -> launchStartActivityForResult(FuZhaiAddActivity::class.java) {
                onLoad()
            }
        }
    }
}

class FuZhaiAdapter : BaseRecyclerAdapter<ItemFuzhaiBinding, FuZhai>() {
    override fun onBindViewHolder(vb: ItemFuzhaiBinding, bean: FuZhai, position: Int) {
        vb.tvPt.text = bean.pingtai
        vb.tvFzsj.text = bean.fzsj
        vb.tvHzsj.text = bean.hzsj
        vb.tvJe.text = bean.jine
    }
}